//
//  ViewController.m
//  AFN_Test
//
//  Created by Guo Rui on 2017/9/8.
//  Copyright © 2017年 GR Harry. All rights reserved.
//

#import "ViewController.h"
#import "AFNetworking/AFNetworking.h"

#define kLoginUrl  @"http://120.25.226.186:32812/login"
#define kUploadUrl @"http://120.25.226.186:32812/upload"

#import "Person.h"

#import "AppDelegate.h"

#import "TFURLSessionManager.h"


@interface ViewController ()
@property (strong, nonatomic) TFURLSessionManager *sessionMager;

@property (strong, nonatomic) id observer;
@end

@implementation ViewController

/**
    http://120.25.226.186:32812/login?username=&pwd=&type=JSON
    http://120.25.226.186:32812/upload
 
 */

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.observer = [[NSNotificationCenter defaultCenter] addObserverForName:TFNetworkingTaskDidCompletionNotification object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) {
        NSLog(@"object : %@", note.object);
        NSLog(@"userInfo : %@", note.userInfo);
    }];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self.observer name:TFNetworkingTaskDidCompletionNotification object:nil];
    NSLog(@"\n************\n %@ dealloc \n************", self.class);
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self postFile];
//    NSMutableArray *arrayM = [NSMutableArray arrayWithCapacity:0];
//    for (int i = 0; i < 5; i++) {
//        [arrayM addObject:@(i)];
//    }
//    
//    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
//    dispatch_async(dispatch_get_global_queue(0, 0), ^{
//        for (NSNumber *num in arrayM) {
//            NSLog(@"%@", num);
//        }
//        NSLog(@"----");
//        dispatch_semaphore_signal(semaphore);
//    });
//    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
//    NSLog(@"+++++++++");
}

- (void)get
{
    /**
        与NSURLSession的比较:
        1. 提供了便利创建NSURLRquest的类AFHTTPRequestSerializer
        1.1 AFJSONRequestSerializer是AFHTTPRequestSerializer的子类，用于将参数变为JSON格式。
     
        2. 下载结果转成了NSArray or NSDicitionary 对象
     */
    
    NSURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:kLoginUrl parameters:@{ @"username" : @"520it", @"pwd" : @"520it" } error:nil];
    
    NSURLSessionDataTask *task = [self.sessionMager dataTaskWithRequest:request uploadProgress:^(NSProgress * _Nonnull uploadProgress) {
        NSLog(@"%lf", uploadProgress.fractionCompleted);
    } downloadProgress:^(NSProgress * _Nonnull downloadProgress) {
        
    } completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        NSLog(@"%@ -- %@", responseObject, [responseObject class]);
    }];
    
    [task resume];
}

- (void)post
{
    NSURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:kLoginUrl parameters:@{ @"username" : @"520it", @"pwd" : @"520it" } error:nil];
    
    NSURLSessionDataTask *task = [self.sessionMager dataTaskWithRequest:request uploadProgress:^(NSProgress * _Nonnull uploadProgress) {
        NSLog(@"%lf", uploadProgress.fractionCompleted);
    } downloadProgress:^(NSProgress * _Nonnull downloadProgress) {
        
    } completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        NSLog(@"%@ -- %@", responseObject, [responseObject class]);
    }];
    self.sessionMager.responseSerializer = [AFJSONResponseSerializer serializer];
    [task resume];
}

- (void)postFile
{
    NSURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:kUploadUrl parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"/Users/guorui/Movies/0226/笔记.zip"] name:@"file" error:nil];
    } error:nil];
    
//    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:kUploadUrl]];
    
//    NSURLSessionDataTask *task = [self.sessionMager dataTaskWithRequest:request uploadProgress:^(NSProgress * _Nonnull uploadProgress) {
//        NSLog(@"%lf", uploadProgress.fractionCompleted);
//    } downloadProgress:^(NSProgress * _Nonnull downloadProgress) {
//        
//    } completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
//        NSLog(@"%@ -- %@", responseObject, [responseObject class]);
//    }];
    
    NSURLSessionUploadTask *task = [self.sessionMager uploadTaskWithRequest:request fromFile:nil uploadProgress:^(NSProgress *uploadProgress) {
                    NSLog(@"%lf", uploadProgress.fractionCompleted);
    } completionHandler:^(NSURLResponse *response, NSURL *fileURL, NSError *error) {
                NSLog(@"%@", fileURL);
    }];
    
    [task resume];
}
//
- (void)download
{
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_02.mp4"]];
    NSURLSessionDownloadTask *task = [self.sessionMager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        NSLog(@"%lf,", downloadProgress.fractionCompleted);
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        NSString *filePath =  [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];
        return [NSURL fileURLWithPath:filePath];
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        NSLog(@"completion -- %@", filePath);
    }];
    
    
//    NSURLSessionDataTask *task = [self.sessionMager dataTaskWithRequest:request uploadProgress:^(NSProgress * _Nonnull uploadProgress) {
//        
//    } downloadProgress:^(NSProgress * _Nonnull downloadProgress) {
//        NSLog(@"%lf", downloadProgress.fractionCompleted);
//    } completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
//        NSLog(@"%@", responseObject);
//    }];
    
    [task resume];
}

- (TFURLSessionManager *)sessionMager
{
    if (nil == _sessionMager) {
        _sessionMager =  [[TFURLSessionManager alloc] initWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    }
    return _sessionMager;
}

@end
